/**
 * @author raelzhu
 * @version $Revision: 1.62 $
 */
Opal.DCMS3.Select = function opal_dcms3_select(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.syncData = function() {
		var value = eval('context.' + this.binding.value);
		value = (value != undefined && value != null) ? value : '';
		for (var i = 0; i < this.element.options.length; i++) {
			var opt = this.element.options[i];
			if (opt.value == value) {
				this.element.selectedIndex = i;
				break;
			}
		}
	};
	
	this.element.onchange = function() {
		Opal.Util._setCursor(this.element);
		$populate_context(this.binding.value, this.element.value);
	}.bind(this);
	
	this.select = function(index) {
		this.element.selectedIndex = index;
		this.element.onchange();
	};
	this.select(this.element.selectedIndex);
	
	this.getSelectedIndex = function() {
		var optionDatas = eval('context.' + this.binding.options) || [];
		return (this.element.options.length > optionDatas.length) ? this.element.selectedIndex - 1 : this.element.selectedIndex;
	};
	
	this.getSelectedData = function() {
		var optionDatas = eval('context.' + this.binding.options) || [];
		return optionDatas[this.getSelectedIndex()];
	};
}
Opal.DCMS3.Select.prototype = Opal.Core.Select.prototype;

Opal.DCMS3.EditPartTable = function(id) {
	Opal.Component.apply(this, arguments);
}
Opal.DCMS3.EditPartTable.prototype = Opal.Core.HTMLComponent;

Opal.DCMS3.Checkbox = function opal_dcms3_checkbox(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	
	var obj = this;
	this._clickHandlers = [];
	this.element.onclick = function(event) {
		Opal.Util._setCursor(obj.element);
		if (obj.element.checked) {
			$populate_context(obj.binding.value, obj.binding.checkedValue);
		} else {
			$populate_context(obj.binding.value, obj.binding.uncheckedValue);
		}
		
		for (var i = 0; i < obj._clickHandlers.length; i++) {
			obj._clickHandlers[i].call(obj, event);
		}
	};
}
Opal.DCMS3.Checkbox.prototype = Opal.Core.HTMLComponent;

Opal.DCMS3.DateLabel = function opal_dcms3_date_label(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.syncData = function() {
		var value = eval('context.' + this.binding.value);
		value = (value != undefined && value != null) ? value : '';
		//value = formatData(parseDate(value), this.format);
		this.element.innerHTML = value;
	}
}
Opal.DCMS3.DateLabel.prototype = Opal.Core.HTMLComponent;

Opal.DCMS3.NumberLabel = function opal_dcms3_number_label(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.syncData = function() {
		var value = eval('context.' + this.binding.value);
		value = (value != undefined && value != null) ? value : '';
		//value = formatNumber(value, this.format);
		this.element.innerHTML = value;
	}
}
Opal.DCMS3.NumberLabel.prototype = Opal.Core.HTMLComponent;

Opal.DCMS3.DictionaryLabel = function opal_dcms3_dictionary_label(id) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.syncData = function() {
		var value = eval('context.' + this.binding.value);
		value = (value != undefined && value != null) ? value : '';
		var list = context.dictionary[this.type] || [];
		var obj = this;
		list.each(function(it) {
			if (it.key == value) {
				obj.element.innerHTML = it.value;
			}
		});
	}
};
Opal.DCMS3.DictionaryLabel.prototype = Opal.Core.HTMLComponent; 

Opal.DCMS3.Date = function opal_dcms3_date(o) {
	Object.extend(this, o);

	this.editor = $(this.id + '_editor');
	this.trigger = $(this.id + '_trigger');
	
	$O.registerComponent(this.id, this);
	$O.registerComponent(this.id + '_editor', this.editor);
	
	var cal = new CalendarPopup();
	cal.showNavigationDropdowns();

	this.trigger.onclick = function() {
		cal.select(this.editor, this.id + '_trigger', this.binding.dateFormat);
	}.bind(this);
	
	this.editor.onblur = function() {
		Opal.Util._setCursor(this.editor);
		var v = this.editor.value;
		if (v.replace(/^\s*/, '') == '') {
			$populate_context(this.binding.value, v);
			return;
		}
		if (!isDate(v, this.binding.dateFormat)) {
			Opal.Util.showMessage(getErrorMessage('VALUE_MUST_BE_DATE', this.binding.caption));
			this.syncData();
			return;
		}
		$populate_context(this.binding.value, formatDate(parseDate(v) || new Date(v), 'yyyy-MM-dd'));
	}.bind(this);
}
Opal.DCMS3.Date.prototype = {
	syncData: function() {
		var value = eval('context.' + this.binding.value);
		value = (value != undefined && value != null) ? value : '';
		if (value == '') {
			this.editor.value = '';
		} else {
			this.editor.value = formatDate(parseDate(value), this.binding.dateFormat);
		}
	},
	isLocked: function() { return this.editor.readOnly == true; },
	lock: function() { this.editor.readOnly = true; this.trigger.disabled = true; },
	unlock: function() { this.editor.readOnly = false; this.trigger.disabled = false; },
	isDisabled: function() { return this.editor.disabled == true; },
	disable: function() { this.editor.disabled = true; this.trigger.disabled = true; },
	enable: function() { this.editor.disabled = false; this.trigger.disabled = false; },
	addEventListener: function(type, handler) {
		//Event.observe(this.editor, type, handler.bindAsEventListener(this));
	}
};

Opal.DCMS3.TabPanel = function(id) {
	Opal.Component.apply(this, arguments);
	
	this.selectedTabIndex = 0;
	
	this.clickTab = function(tabIndex) {
		if (this.selectedTabIndex != tabIndex) {
			$(this.id + '_' + this.selectedTabIndex).className = 'tabPanel_tab';
			this.selectedTabIndex = tabIndex;
			$(this.id + '_' + this.selectedTabIndex).className = 'tabPanel_selectedTab';
		}
	}
}
Opal.DCMS3.TabPanel.prototype = {
	addTab: function() {
		
	},
	addEventListener: function(index, type, handler) {
		this[type + 'Handlers' + index] = this[type + 'Handlers' + index] || [];
		this[type + 'Handlers' + index].push(handler);
	},
	switchTo: function(url, index) {
		try {
			(this['beforeSwitchHandlers' + index] || []).each(function(it) {
				it();
			});
		} catch (e) {
			if (typeof e == 'function')
				e();
			else
				alert(e);
			return false;
		}
		$(this.id + '_tab' + (this.activeTabIndex || 0)).className = 'tabPanel_tab';
		$(this.id + '_tab' + index).className = 'tabPanel_selectedTab';
		this.activeTabIndex = index;
		window.frames['tabFrame'].location.replace(url);
	}
}

Opal.DCMS3.Tab = function(id) {
	Opal.Component.apply(this, arguments);
	if (this.element.className == 'tabPanel_selectedTab') {
		Opal.DCMS3.Tab.currentTab = this.element;
	}
	
	Event.observe(this.element, 'click', this.switchTo.bindAsEventListener(this));
}
Opal.DCMS3.Tab.prototype = {
	setURL: function(url) { this.url = url; },
	setTarget: function(target) { this.target = target },
	addEventListener: function(type, handler) {
		this[type + 'Handlers'] = this[type + 'Handlers'] || [];
		this[type + 'Handlers'].push(handler);
	},
	switchTo: function() {
		try {
			(this['switchHandlers'] || []).each(function(it) {
				it();
			});
		} catch (e) {
			if (typeof e == 'function')
				e();
			else
				alert(e);
			return false;
		}
		if (Opal.DCMS3.Tab.currentTab != undefined) {
			Opal.DCMS3.Tab.currentTab.className = 'tabPanel_tab';
		}
		this.element.className = 'tabPanel_selectedTab';
		Opal.DCMS3.Tab.currentTab = this.element;
		window.frames['tabFrame'].location.replace(this.url);
	}
}

Opal.DCMS3.SummarySearch = function opal_dcms3_summary_search(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	var arr = $(this.id + '_searchNameAlias').value.split('^');
	var name = arr[0] || '';
	var type = arr[1] || 'varchar';
	context.searchname = name;
	context.searchtype = type;
}
Opal.DCMS3.SummarySearch.prototype = {
	init: function() {
		var arr = $(this.id + '_searchNameAlias').value.split('^');
		var name = arr[0] || '';
		var type = arr[1] || 'varchar';
		context.searchname = name;
		context.searchtype = type;
		context.searchvalue = '';
		context.searchvalue1 = '';
		context.searchvalue2 = '';
		switch(type) {
			case 'integer':
				$O(this.id + '_intValue1').syncData();
				$O(this.id + '_intValue2').syncData();
				
				$(this.id + '_span').style.display = 'none';
				$(this.id + '_intSpan').style.display = '';
				$(this.id + '_numberSpan').style.display = 'none';
				$(this.id + '_dateSpan').style.display = 'none';
				break;
			case 'double':
				$O(this.id + '_numberValue1').syncData();
				$O(this.id + '_numberValue2').syncData();
				
				$(this.id + '_span').style.display = 'none';
				$(this.id + '_intSpan').style.display = 'none';
				$(this.id + '_numberSpan').style.display = '';
				$(this.id + '_dateSpan').style.display = 'none';
				break;
			case 'date':
				$O(this.id + '_dateValue1').syncData();
				$O(this.id + '_dateValue2').syncData();
				
				$(this.id + '_span').style.display = 'none';
				$(this.id + '_intSpan').style.display = 'none';
				$(this.id + '_numberSpan').style.display = 'none';
				$(this.id + '_dateSpan').style.display = '';
				break;
			default:
				$O(this.id + '_value').syncData();
				
				$(this.id + '_span').style.display = '';
				$(this.id + '_intSpan').style.display = 'none';
				$(this.id + '_numberSpan').style.display = 'none';
				$(this.id + '_dateSpan').style.display = 'none';
				break;
		}
	}
};

Opal.DCMS3.Summary = function opal_dcms3_summary(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
}
Opal.DCMS3.Summary.prototype = {
	addEventListener: function(index, type, handler) {
		this[type + 'Handlers' + index] = this[type + 'Handlers' + index] || [];
		this[type + 'Handlers' + index].push(handler);
	},
	
	hilite: function(index) { $(this.id + '_body_' + index).className = 'summary_hoveredRow'; },
	restore: function(index) { $(this.id + '_body_' + index).className = 'summary_bodyRow' + (index % 2); },
	
	clickRow: function(index) {
		var cursor = $(this.id + '_cursor' + index);
		if (cursor && !cursor.disabled && cursor.type == 'radio') {
			cursor.click();
		}
		(this['clickHandlers'] || []).each(function(it) { it(); });
	},
	
	toggleSelectAll: function() {
		var table = this.element;
		var rows = table.tBodies[0].rows;
		var obj = this;
		var cursorAll = $(this.id + '_select_all');
		$A(table.tBodies[0].rows).each(function(row, index) {
			var cursor = $(obj.id + '_cursor' + index);
			if (cursor && !cursor.disabled && cursor.type == 'checkbox') {
				cursor.checked = cursorAll.checked;
			}
		});
	},
	
	getDataByColumnName: function(name) {
		var result = [];
		try {
			var obj = this;
			var datas = context[this.binding.items];
			$A(datas).each(function(item, index) {
				var cursor = $(obj.id + '_cursor' + index);
				if (cursor && !cursor.disabled && cursor.checked) {
					result.push(item[name]);
				}
			});
		} catch(e) {}
		return result;
	},
	
	getData: function() {
		var result = [];
		try {
			var obj = this;
			var datas = context[this.binding.items];
			$A(datas).each(function(item, index) {
				var cursor = $(obj.id + '_cursor' + index);
				if (cursor && !cursor.disabled && cursor.checked) {
					result.push(item);
				}
			});
		} catch(e) {}
		return result;
	},
	
	getSelectedIndex: function() {
		var result = [];
		try {
			var obj = this;
			var datas = context[this.binding.items];
			$A(datas).each(function(item, index) {
				var cursor = $(obj.id + '_cursor' + index);
				if (cursor && !cursor.disabled && cursor.checked) {
					result.push(index);
				}
			});
		} catch(e) {}
		return result;
	},
	
	getSelectedDatasByColumnName: function(name) {
		this.getDataByColumnName(name);
	},
	
	getSelectedDatas: function() {
		this.getData();
	},
	
	getSelectedIndexs: function() {
		this.getSelectedIndex();
	}
};

Opal.DCMS3.EditGrid = function opal_dcms3_edit_grid(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.hilite = function(index, skin) { $(this.id + '_body_row' + index).className = 'editGrid_hoveredRow_' + skin ; };
	this.restore = function(index, skin) { $(this.id + '_body_row' + index).className = 'editGrid_bodyRow' + (index % 2) + '_' + skin ; };
}
Opal.DCMS3.EditGrid.prototype = Opal.DCMS3.Summary.prototype;

Opal.DCMS3.IntEditor = function opal_dcms3_int_editor(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.element.onchange = function() {
		var	value = this.element.value;
		if (isNaN(parseInt(value)) && value.toString().replace(/^\s*/, '') != '') {
			Opal.Util.showMessage(getErrorMessage('VALUE_MUST_BE_INT', this.caption));
			this.syncData();
		} else if (value.toString().indexOf(' ') == 0 || value.toString() == '') {
      		Opal.Util.showMessage(getErrorMessage('VALUE_MUST_BE_INT', this.caption));
      		this.syncData();
    	} else {
			Opal.Util._setCursor(this.element);
			$populate_context(this.binding.value, parseInt(value).toString());
			this.syncData();
		}
	}.bind(this);
}
Opal.DCMS3.IntEditor.prototype = Opal.Core.HTMLComponent;

Opal.DCMS3.NumberEditor = function opal_dcms3_number_editor(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.element.onchange = function() {
		var	value = this.element.value;
		if (isNaN(Number(value)) && value.toString().replace(/^\s*/, '') != '') {
			Opal.Util.showMessage(getErrorMessage('VALUE_MUST_BE_NUMBER', this.caption));
			this.syncData();
		} else if (value.toString().indexOf(' ') == 0 || value.toString() == '') {
      		Opal.Util.showMessage(getErrorMessage('VALUE_MUST_BE_NUMBER', this.caption));
      		this.syncData();
    	} else {
			Opal.Util._setCursor(this.element);
			$populate_context(this.binding.value, Number(value).toString());
			this.syncData();
		}
	}.bind(this);
}
Opal.DCMS3.NumberEditor.prototype = Opal.Core.HTMLComponent;

//incubator
Opal.DCMS3.MultiSelectedTree = function opal_dcms3_multiselected_tree(o) {
	Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this.nodeId = (this.nodeId != undefined && this.nodeId != null) ? this.nodeId  : 'id';
	this.parentNodeId = (this.parentNodeId != undefined && this.parentNodeId != null) ? this.parentNodeId  : 'parentId';
	this.nodeGrade = (this.nodeGrade != undefined && this.nodeGrade != null) ? this.nodeGrade  : 'grade';
	
	this.nodesMap = {};
	this.selectedDatasMap = {};
	
	this.datas = eval('context.' + this.binding.value);
	this.selectedIds = eval('context.' + this.binding.selectedIds);
	this.datas = (this.datas != undefined && this.datas != null) ? this.datas : [];
	this.selectedIds = (this.selectedIds != undefined && this.selectedIds != null) ? this.selectedIds : [];
	
  	this.tree = new YAHOO.widget.TreeView(this.id);
  
  	try{
    	var canBeClickd = eval( this.id + '_canBeClicked');
		if (typeof canBeClickd == 'function') {
	      this.nodeCanBeClicked = canBeClickd;
	    }
  	} catch(e) {
	    Opal.Log.warn(e);
	}
	
	this.addTreeNodes = function addTreeNodes(rootNode) {
		var nodeId = this.nodeId;
		var parentId = this.parentNodeId;
		var nodeGrade = this.nodeGrade;
		
		//var firstNode = new YAHOO.widget.TaskNode({label:'root'}, rootNode, false);
		
		for(var i = 0; i < this.datas.length; i++) {
			var tmpNode;
			if(this.datas[i][nodeGrade] == this.datas[0][nodeGrade]) {
				tmpNode = new YAHOO.widget.TaskNode(this.datas[i], rootNode, false);
			} else {
				tmpNode = new YAHOO.widget.TaskNode(this.datas[i], this.nodesMap[this.datas[i][parentId]], false);
			}
			if($A(this.selectedIds).indexOf(this.datas[i][nodeId]) > -1) {
			 tmpNode.check();
      		}
      		tmpNode.canBeClicked = (this.nodeCanBeClicked != undefined) ? this.nodeCanBeClicked : tmpNode.canBeClicked;
			this.nodesMap[this.datas[i][nodeId]] = tmpNode;
		}
	}.bind(this);
	
	this.syncSelectedNodes = function(node) {
		if (node.checkState == 2) {
		this.selectedDatasMap[node.data[this.nodeId]] = node.data;
		} else {
			this.selectedDatasMap[node.data[this.nodeId]] = null;
		}
	}.bind(this);
	this.tree.subscribe('checkClick',this.syncSelectedNodes);
	
	this.addTreeNodes(this.tree.getRoot());
	this.tree.draw();
}
Opal.DCMS3.MultiSelectedTree.prototype = {
  	getSelectedDatas: function() {
	var datas = $H(this.selectedDatasMap).values();
	var selectedDatas = [];
	for (var i = 0; i < datas.length; i++) {
		var data = datas[i];
		if (data != null) {
			selectedDatas.push(data);
		}
	}
    return selectedDatas;
  }
};

Opal.DCMS3.SimpleTree = function opal_dcms3_simple_tree(o) {
  Object.extend(this, o);
	this.element = $(this.id);
	$O.registerComponent(this.id, this);
	
	this._init(o);
}
Opal.DCMS3.SimpleTree.prototype = {
  id: null,
  nodeId: null,
  parentNodeId: null,
  nodeGrade: null,
  nodesMap: {},
  
  datas: null,
  selectedId: null,
  selectedNode: null,
  
  tree: null,
  
  onLabelClick: null,
  
  _init: function(o) {
    this.id = o.id;
    this.nodeId = (o.nodeId != undefined && o.nodeId != null) ? o.nodeId  : 'id';
	this.parentNodeId = (o.parentNodeId != undefined && o.parentNodeId != null) ? o.parentNodeId  : 'parentId';
    this.nodeGrade = (o.nodeGrade != undefined && o.nodeGrade != null) ? o.nodeGrade  : 'grade';
    
    this.datas = eval('context.' + o.binding.value);
    this.selectedId = eval('context.' + o.binding.selectedId);
    this.datas = (this.datas != undefined && this.datas != null) ? this.datas : [];
    this.selectedId = (this.selectedId != undefined && this.selectedId != null) ? this.selectedId : null;
    
    try {
    	var onLabelClick = eval(o.labelClick);
  		if (typeof onLabelClick == 'function') {
  	      this.onLabelClick = onLabelClick;
  	  }
    } catch(e) {
  	    Opal.Log.warn(e);
  	}
    
    this.tree = new YAHOO.widget.TreeView(this.id);
    this._addTreeNodes(this.tree.getRoot());
    this.tree.subscribe("labelClick", this._labelClickHandler, this, true);
    this.tree.draw();
    if (this.selectedId != null) {
      this.selectTreeNode(this.selectedId);
    }
  },
  
  _labelClickHandler: function(node) {
    this.selectTreeNode(node.data[this.nodeId]);
    if (this.onLabelClick) this.onLabelClick(node.data);
  },
  
  _addTreeNodes: function(rootNode) {
    var nodeId = this.nodeId;
		var parentId = this.parentNodeId;
		var nodeGrade = this.nodeGrade;
		
		for(var i = 0; i < this.datas.length; i++) {
			var tmpNode;
			var data = this.datas[i];
			data.href = (data.href != undefined && data.href != null) ? data.href : '#';
			if(data[nodeGrade] == this.datas[0][nodeGrade]) {
				tmpNode = new YAHOO.widget.TextNode(data, rootNode, false);
			} else {
				tmpNode = new YAHOO.widget.TextNode(data, this.nodesMap[data[parentId]], false);
			}
			this.nodesMap[data[nodeId]] = tmpNode;
		}
  },
  
  selectTreeNode: function(id) {
    if (this.selectedNode) YAHOO.util.Dom.setStyle(this.selectedNode.getLabelEl(), 'color', '');
    this.selectedId = id;
    this.selectedNode = this.nodesMap[id];
    if (this.selectedNode) {
      this.selectedNode.toggle();
      YAHOO.util.Dom.setStyle(this.selectedNode.getLabelEl(), 'color', '#6699ff');
    }
  },
  
  getSelectedData: function() {
    if (this.selectedNode) {
      return this.selectedNode.data;
    } else {
      return {};
    }
  }
};
